<template>
  <div>
    <el-input size="mini" v-model="searchName" style="width: 400px" placeholder="输入开局编号或者局面的中英文"></el-input>
    <p class="firstLine">开局分类: </p>
    <el-select v-model="selectOpen" placeholder="请选择" size="mini">
      <el-option
          v-for="item in openOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-button class="firstLine" size="mini" type="primary" @click="searchFen">查询</el-button>
    <el-tooltip class="item" effect="dark" content="翻转黑白朝向" placement="top">
      <el-button type="info" icon="el-icon-refresh" class="f-m-5" size="small" @click="reverseBoard"></el-button>
    </el-tooltip>
    <el-row>
      <el-col :span=7>
        <chessboard :onPromotion="promote" :free="ifFree" :orientation="boardColor" @onMove="getInfo" :fen="currentFen" />
      </el-col>
      <el-col :span=6>
        <h5>大数据:</h5>
        <el-table :data="bigData" stripe :height="250" class="f-m-5" v-loading="bigDataLoading" element-loading-text="拼命加载中">
          <el-table-column
              prop="move"
              label="走法"
              width="70">
          </el-table-column>
          <el-table-column
              prop="result"
              label="白/平/黑"
              >
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span=11>
        <h5>名局: </h5>
        <el-table :data="topGames" stripe border  :height="250" class="f-m-5" v-loading="bigDataLoading" element-loading-text="拼命加载中">
          <el-table-column
              prop="white"
              label="白方"
              width="150">
          </el-table-column>
          <el-table-column
              prop="black"
              label="黑方"
              width="150">
          </el-table-column>
          <el-table-column
              prop="result"
              label="结果"
          >
          </el-table-column>
          <el-table-column
              prop="date"
              label="年月"
          >
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <h5>数据库：</h5>
    <el-table :data="dbData" stripe border :height="250" >
      <el-table-column
          prop="move"
          label="走法"
          width="70">
      </el-table-column>
      <el-table-column
          prop="name"
          label="局面名称"
          width="350">
      </el-table-column>
      <el-table-column
          prop="nameEn"
          label="局面英文名"
          width="400">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="更新时间"
          >
      </el-table-column>
      <el-table-column
          prop="value"
          label="数据库评分"
          width="130">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="100"
      >
        <template slot-scope="scope">
          <el-button @click="chooseStep(scope.row)" type="text" size="mini">选择</el-button>
          <el-button type="text" size="mini" @click="showEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        :visible.sync="saveModal"
        title="保存局面"
        width="80%" center
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <el-row>
        <el-col :span="12">
          <h5>当前局面</h5>
          <chessboard class="f-m-r-5" :free="false" :fen="beforeFen"/>
        </el-col>
        <el-col :span="12">
          <h5>下一步</h5>
          <chessboard class="f-m-l-5" :free="false" :fen="afterFen"/>
        </el-col>
      </el-row>
      <p class="f-m-5">局面中文名:
        <el-input class="f-m-5" v-model="saveFenName" style="width: 300px"></el-input>
      </p>
      <p class="f-m-5">局面英文名:
        <el-input class="f-m-5" v-model="saveFenNameEn" style="width: 300px"></el-input>
      </p>
      <p class="f-m-5">局面评分:
        <el-input class="f-m-5" v-model="saveValue" style="width: 300px"></el-input>
      </p>
      <p class="f-m-5">下一步走法: {{ saveMove }}</p>
      <el-button @click="saveModal=false" size="mini">取消</el-button>
      <el-button type="primary" @click="saveFen" size="mini">确定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {chessboard} from "vue-chessboard";
import * as utils from "@/lib/utils";
import {invoke} from "@/lib/utils";
import {DEFAULT_CONFIG} from "@/lib/constants";
import path from "path";
import Sqlite from "@/lib/sqlite";
import Chessmate from "@/lib/chessmate";
import emitvue from "@/lib/emitvue";
import Database from "@/lib/database";
import {getBigData} from "@/lib/reptile";

export default {
  name: "Database",
  data() {
    return {
      isDev: false,
      appPath: null,
      currentFen: '',
      openFen: utils.newGame,
      ifFree: false,//随意走子
      boardColor: 'white',//棋盘朝向
      activeName: 'analyze',
      // 系统设置
      settingForm: {
        dbPath: '',
        enginePath: '',
        analyzeSpeed: '快速',
        mistakeThreshold: 0.5,
        blunderThreshold: 1
      },
      dbData: [],
      // 大数据和名局
      bigData: [],
      topGames: [],

      // 保存对话框
      saveModal: false,
      beforeFen: '',
      afterFen: '', // 保存后的局面
      saveFenName: '', // 中文
      saveFenNameEn: '', // 英文
      saveValue: '',
      saveMove: '',
      // 查询
      searchName: '',
      openOptions: [
        {value: 'A', label: 'A类 不规则开局'},
        {value: 'B', label: 'B类 半开放性布局'},
        {value: 'C', label: 'C类 开放性布局'},
        {value: 'D', label: 'D类 以1.d4 d5开局的后翼弃兵开局'},
        {value: 'E', label: 'E类 1.d4 Nf6 2. c4 e6或者g6开局的封闭性布局'},
      ],
      selectOpen: null,
      bigDataLoading: false
    }
  },
  methods: {
    async getInfo(data) {
      if (!data.history?.length) return
      this.currentFen = data.fen
      this.dbData = await Database.searchFen(this.currentFen)
      this.bigDataLoading = true
      const {bigData, topGames } = await getBigData(this.currentFen)
      this.bigData = bigData
      this.topGames = topGames
      this.bigDataLoading = false
    },
    // 升变
    promote() {
      if (confirm("是否升变为后？")) {
        return 'q'
      } else {
        if (confirm("是否升变为车？")) {
          return 'r'
        } else {
          if (confirm("是否升变为马？")) {
            return 'n'
          } else {
            if (confirm("是否升变为象？")) {
              return 'b'
            }
          }
        }
      }
      return 'q'
    },
    async getSetting() {
      let config = await invoke('get', {name: 'setting', type: 'database'})
      if (!config) {
        await invoke('set', JSON.stringify({name: 'setting', type: 'database', dbPath: '', enginePath: ''}))
      } else {
        // if (!utils.existValue(config.defaultValue) || config.defaultValue === true) {
        //   config = DEFAULT_CONFIG
        //   config.dbPath = path.join(this.appPath, config.dbPath)
        //   config.enginePath = path.join(this.appPath, config.enginePath)
        // }
        const chessConfig = {
          path: config.enginePath,
          analyzeSpeed: config.analyzeSpeed,
          blunderThreshold: config.blunderThreshold,
          mistakeThreshold: config.mistakeThreshold,
        }
        await Chessmate.init(chessConfig)
      }
    },
    // 查询数据库
    async searchFen() {
      if ((this.searchName === '' || !this.searchName) && !this.selectOpen ) return this.$notify({duration: 1000, title: '通知', message: "请先选择查询条件", type: 'warning'})
      this.dbData = await Database.searchByName(this.searchName, this.selectOpen)
      this.bigDataLoading = true
      const {bigData, topGames } = await getBigData(this.currentFen)
      this.bigData = bigData
      this.topGames = topGames
      this.bigDataLoading = false
    },
    //
    async showEdit(data) {
      this.saveModal = true
      this.saveValue = data.value || data.dbValue || ''
      this.saveMove = data.move
      this.saveFenNameEn = data.nameEn || ''
      this.saveFenName = data.name || ''
      await utils.sleep(200)
      this.currentFen = this.currentFen === '' ? this.openFen : this.currentFen
      this.beforeFen = Chessmate.move(this.currentFen, null)    // 这行代码是为了避免chessboard的Bug
      this.afterFen = Chessmate.move(this.currentFen, data.move)
    },
    // 保存fen至数据库
    async saveFen() {
      this.saveModal = false
      const data = {
        fen: this.beforeFen,
        value: this.saveValue,
        move: this.saveMove,
        createTime: utils.getCurrentTime(),
        name: this.saveFenName,
        nameEn: this.saveFenNameEn,
      }
      await Database.saveFen(data)
      this.$notify({duration: 1000, title: '通知', message: "保存成功", type: 'success'})
      this.beforeFen = ''
      this.saveValue = ''
      this.saveMove = ''
      this.saveFenName = ''
      this.saveFenNameEn = ''
    },
    // 选择数据库的这步棋
    async chooseStep(data) {
      this.currentFen = Chessmate.move(data.fen, data.move)
      this.dbData = await Database.searchFen(this.currentFen)
      this.bigDataLoading = true
      const {bigData, topGames } = await getBigData(this.currentFen)
      this.bigData = bigData
      this.topGames = topGames
      this.bigDataLoading = false
    },
    reverseBoard() {
      this.boardColor = this.boardColor === 'white' ? 'black' : 'white';
    }
  },
  async mounted() {
    emitvue.$on('databaseActive', async ()=> {
      this.currentFen = this.openFen
      this.dbData = await Database.searchFen(this.currentFen)
    })
    if (location.protocol.indexOf('http') !== -1) {
      this.isDev = true
    }
    this.appPath = await invoke('getCurrentPath', null)
    await this.getSetting()
    this.dbData = await Database.searchFen(this.currentFen)
    const {bigData, topGames } = await getBigData(this.currentFen)
    this.bigData = bigData
    this.topGames = topGames
  },
  components: {
    chessboard
  },
}
</script>


<style scoped>
.firstLine {
  display: inline-block;
  margin: 5px;
}
body {
  margin: 0;
}
</style>